from ET import GetText
import sys,regsub,regex,time
import RegisterImpl,RegisterInit
class StyleMatcher:
	pos=-1
	def __init__(self,style,matcher):
		self.style=style
		self.search=matcher.search
		self.matched=matcher.matched
class SearchOrder:
	def __init__(self,styles):
		l=[]
		for style,matcher in styles:
			l.append(StyleMatcher(style,matcher))
		self.styles=l
	def search(self,str,start):
		result=0x0FFFFFFF
		found=None
		for m in self.styles[:]:
			pos=m.pos
			if pos<start:
				try:
					pos=m.search(str, start)
				except:
					print "SyntaxHighlight failure",m
					pos=-1
				if pos>=0:
					# aha we have a match, but now we need to go to the
					# real match start
					m.matches=m.matched()
					pos=m.pos=m.matches[0]
			if pos<0:
				del self.styles[self.styles.index(m)]
			elif pos<result:
				found=m
				result=pos
		if not found:
			return -1
		self.matches=found.matches
		self.style=found.style
		return result

def keywords(prog, str, result):
	start = 0
	first = 1
	l=len(str)
	search=prog.search
	while search(str, start) >= 0:
		a, b  = prog.matches
		if a == b == start and not first:
			if start >= l or search(str, start+1) < 0:
				break
			a,b  = prog.matches
		result.append((a,b,prog.style))
		start = b
		first = 0

def LoadSyntaxDesc(filetype):
	list=RegisterImpl._syntax.GetAll(filetype)
	if list:
		return list[0]()
	return
def FindSyntaxDesc(filetype,filetypename,filename):
	RegisterInit.ReInit()
	syntaxdesc=LoadSyntaxDesc(filetype)
	if syntaxdesc is None:
		syntaxdesc=LoadSyntaxDesc(filetypename)
	if syntaxdesc is None:
		return []
	return syntaxdesc
#import SyntaxDesc
#reload(SyntaxDesc)
_last_text=""
_last_list=[]
highlight_comments=1
def SyntaxHighlight(filetype,filetypename,filename,do_highlight_comments=1):
	"""Gets a filename and returns a list of (start_pos,end_pos,CharStyle).

	This function is called by SNiFF+ to get the syntax highlighting"""
	global highlight_comments
	highlight_comments=do_highlight_comments
#	print "highlight_comments", highlight_comments
#	t0=time.time()
	#print `filetype`,`filetypename`,filename
	global _last_text,_last_list
	text=GetText()
	if text==_last_text:
		return _last_list
	styles=FindSyntaxDesc(filetype,filetypename,filename)
	result=[]
#	t0=time.time()
#	print "SyntaxHighlight..."
	m=SearchOrder(styles)
	keywords(m,text,result)
#	print "...Done",len(result),time.time()-t0
	_last_text=text
	_last_list=result
	#print result
	return result

